#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random
import time

def clear_screen():
    import os
    os.system('cls' if os.name == 'nt' else 'clear')

def print_with_delay(text, delay=0.03):
    for char in text:
        print(char, end='', flush=True)
        time.sleep(delay)
    print()

def level_1():
    """第一关：简单的数字解密"""
    clear_screen()
    print_with_delay("=== 第一关：数字密码 ===")
    print_with_delay("线索：密码是一个3位数字，每个数字都比前一个数字大2")
    print_with_delay("例如：如果第一个数字是1，那么密码就是135")
    print_with_delay("提示：第一个数字是随机生成的（1-6之间）")
    
    first_num = random.randint(1, 6)
    password = f"{first_num}{first_num+2}{first_num+4}"
    
    attempts = 3
    while attempts > 0:
        print_with_delay(f"\n你还有 {attempts} 次机会")
        guess = input("请输入3位数字密码：")
        
        if guess == password:
            print_with_delay("✓ 恭喜！密码正确！")
            return True
        else:
            print_with_delay("✗ 密码错误！")
            attempts -= 1
    
    print_with_delay(f"\n游戏结束！正确答案是：{password}")
    return False

def level_2():
    """第二关：字母替换密码"""
    clear_screen()
    print_with_delay("=== 第二关：凯撒密码 ===")
    print_with_delay("线索：每个字母向后移动3位")
    print_with_delay("例如：A→D, B→E, C→F")
    print_with_delay("加密后的密码：KHOOR")
    
    encrypted = "KHOOR"
    password = "HELLO"
    
    attempts = 3
    while attempts > 0:
        print_with_delay(f"\n你还有 {attempts} 次机会")
        guess = input("请输入解密后的单词：").upper()
        
        if guess == password:
            print_with_delay("✓ 太棒了！解密成功！")
            return True
        else:
            print_with_delay("✗ 解密错误！")
            attempts -= 1
            
            if attempts > 0:
                hint = input("需要提示吗？(y/n): ").lower()
                if hint == 'y':
                    print_with_delay("提示：想想字母表中的位置，A=1, B=2...")
    
    print_with_delay(f"\n游戏结束！正确答案是：{password}")
    return False

def level_3():
    """第三关：数学谜题"""
    clear_screen()
    print_with_delay("=== 第三关：数学密码 ===")
    
    a = random.randint(1, 9)
    b = random.randint(1, 9)
    c = random.randint(1, 9)
    
    result = a * b + c
    
    print_with_delay(f"线索：密码由3个1-9的数字组成")
    print_with_delay(f"条件：第一个数字 × 第二个数字 + 第三个数字 = {result}")
    print_with_delay("例如：如果结果是15，可能的密码是345（3×4+3=15）")
    
    password = f"{a}{b}{c}"
    
    attempts = 3
    while attempts > 0:
        print_with_delay(f"\n你还有 {attempts} 次机会")
        guess = input("请输入3位数字密码：")
        
        if len(guess) != 3 or not guess.isdigit():
            print_with_delay("✗ 请输入3位数字！")
            continue
            
        x, y, z = int(guess[0]), int(guess[1]), int(guess[2])
        
        if x * y + z == result:
            print_with_delay("✓ 数学天才！密码正确！")
            return True
        else:
            print_with_delay("✗ 计算结果不正确！")
            attempts -= 1
    
    print_with_delay(f"\n游戏结束！正确答案是：{password}")
    return False

def final_level():
    """最终关卡：组合密码"""
    clear_screen()
    print_with_delay("=== 最终关卡：终极挑战 ===")
    print_with_delay("线索：这个密码结合了前三关的元素")
    print_with_delay("1. 第一个数字：比5大2的数字")
    print_with_delay("2. 第二个部分：解密'ZRUOG'（凯撒密码，移动3位）")
    print_with_delay("3. 第三个数字：使得 第一个数字 × 3 + 第三个数字 = 30")
    
    part1 = "7"  # 5+2
    part2 = "WORLD"  # ZRUOG解密
    part3 = "9"  # 7×3+9=30
    password = part1 + part2.lower() + part3
    
    attempts = 3
    while attempts > 0:
        print_with_delay(f"\n你还有 {attempts} 次机会")
        guess = input("请输入完整密码（数字+单词+数字）：")
        
        if guess.lower() == password.lower():
            print_with_delay("🎉 恭喜你！你完成了所有关卡！")
            print_with_delay("你是真正的解密大师！")
            return True
        else:
            print_with_delay("✗ 密码错误！")
            attempts -= 1
            
            if attempts == 2:
                print_with_delay("提示：第一个数字是7")
            elif attempts == 1:
                print_with_delay("提示：单词部分是'world'")
    
    print_with_delay(f"\n游戏结束！正确答案是：{password}")
    return False

def main():
    clear_screen()
    print_with_delay("🔐 欢迎来到解密小游戏！")
    print_with_delay("你将面对4个不同难度的解密挑战")
    print_with_delay("每个关卡有3次尝试机会")
    print_with_delay("准备好了吗？让我们开始吧！")
    
    input("\n按回车键开始游戏...")
    
    levels = [level_1, level_2, level_3, final_level]
    level_names = ["第一关", "第二关", "第三关", "最终关卡"]
    
    for i, level_func in enumerate(levels):
        print_with_delay(f"\n{'='*40}")
        print_with_delay(f"开始 {level_names[i]}")
        print_with_delay(f"{'='*40}")
        
        if not level_func():
            print_with_delay("\n游戏失败！再接再厉！")
            break
        
        if i < len(levels) - 1:
            input("\n按回车键进入下一关...")
    else:
        print_with_delay("\n🎊 恭喜你通关了整个游戏！")
        print_with_delay("你展现出了卓越的解密能力！")
    
    print_with_delay("\n感谢游玩！")
    input("按回车键退出游戏...")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n游戏被中断。再见！")
    except Exception as e:
        print(f"\n发生错误：{e}")